<?php
/**
 * Created by PhpStorm.
 * User: wxy
 * Date: 2018/11/23
 * Time: 13:38
 */

namespace frontend\modules\common\component;

use Yii;
use yii\base\UserException;
use yii\web\ErrorHandler as BaseErrorHandler;
use yii\web\Response;


class ErrorHandler extends BaseErrorHandler
{

    protected function renderException($exception)
    {

        $response = new Response();

        $response->setStatusCodeByException($exception);

        $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
        if (Yii::$app->request->getIsAjax()) {
            $msg = $exception->getMessage();

            if (!YII_DEBUG) {
                $msg = '服务器内部错误';
            }
            exit(json_encode([
                'status' => $exception->getCode(),
                'msg' => $msg
            ]));
        }

        if ($useErrorView && $this->errorAction !== null) {

            $result = Yii::$app->runAction($this->errorAction);

            if ($result instanceof Response) {
                $response = $result;
            } else {
                $response->data = $result;
            }
        } elseif ($response->format === Response::FORMAT_HTML) {

            if ($this->shouldRenderSimpleHtml()) {
                // AJAX request
                $response->data = '<pre>' . $this->htmlEncode(static::convertExceptionToString($exception)) . '</pre>';
            } else {
                // if there is an error during error rendering it's useful to
                // display PHP error in debug mode instead of a blank screen
                if (YII_DEBUG) {
                    ini_set('display_errors', 1);
                }
                $file = $useErrorView ? $this->errorView : $this->exceptionView;
                $response->data = $this->renderFile($file, [
                    'exception' => $exception,
                ]);
            }
        } elseif ($response->format === Response::FORMAT_RAW) {
            $response->data = static::convertExceptionToString($exception);
        } else {
            $response->data = $this->convertExceptionToArray($exception);
        }

        $response->send();
    }

}